package com.dgut.common.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dgut.common.entity.AdminUser;
import com.dgut.common.entity.WxUser;
import com.dgut.common.mapper.AdminUserMapper;
import com.dgut.common.mapper.WxUserMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * JWT工具类
 * @author IT00ZYQ
 * @date 2021/4/5 12:32
 **/
@Component
public class JwtUtil {

    private static WxUserMapper wxUserMapper;
    private static AdminUserMapper adminUserMapper;

    private final WxUserMapper userMapper;
    private final AdminUserMapper adminMapper;



    public JwtUtil(WxUserMapper userMapper, AdminUserMapper adminMapper) {
        this.userMapper = userMapper;
        this.adminMapper = adminMapper;
    }

    @PostConstruct
    void init(){
        wxUserMapper = userMapper;
        adminUserMapper = adminMapper;
    }

    /**
     * 密钥
     */
    private static String secret = "dgut20210405";
    /**
     * 字段名
     */
    public final static String HEADER = "token";

    /**
     * @descrition:  根据身份ID标识，生成Token
     * @param identityId :
     * @return : java.lang.String
     */
    public static String getToken (String identityId){
        Date nowDate = new Date();
        /**
         * 超时时间
         */
        long expire = 86400L;
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(identityId)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 获取 Token 中注册信息
     * @param token
     */
    public static Claims getTokenClaim (String token) {
        try {
            return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e){
            e.printStackTrace();
            throw e;
        }
    }
    /**
     * @descrition:  Token 是否过期验证
     * @param expirationTime :
     * @return : boolean
     */
    public boolean isTokenExpired (Date expirationTime) {
        return expirationTime.before(new Date());
    }

    /**
     * 根据token获取用户信息
     * @param token
     * @return
     */
    public static WxUser getUser(String token){
        Claims claim = getTokenClaim(token);
        String openid = claim.getSubject();
        QueryWrapper<WxUser> wrapper = new QueryWrapper<>();
        wrapper.eq("open_id", openid);
        WxUser user = wxUserMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(user)){
            throw new ApiException(ErrorEnum.USER_NO_EXIST);
        }
        return user;
    }

    /**
     * 根据token获取管理员信息
     * @param token
     * @return
     */
    public static AdminUser getAdmin(String token){
        Claims claim = getTokenClaim(token);
        String username = claim.getSubject();
        QueryWrapper<AdminUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        AdminUser adminUser = adminUserMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(adminUser)){
            throw new ApiException(ErrorEnum.USER_NO_EXIST);
        }
        return adminUser;
    }
}